import React, { useState, useEffect } from "react";
import { connect } from "react-redux";
import {
  getColumns,
  typeOptions,
  statusOptions,
  departmentOptions,
} from "./softwareCopyrightColumns";
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  DatePicker,
  Upload,
  message,
  Select,
  Switch,
  InputNumber,
  Row,
  Col,
  Tag,
  Tooltip,
} from "antd";
import {
  UploadOutlined,
  SearchOutlined,
  DownloadOutlined,
  PlusOutlined,
  FileExcelOutlined,
} from "@ant-design/icons";
import dayjs from "dayjs";
import * as XLSX from 'xlsx';
import { decodeFile } from '../../../utils/decode';
import {
  getSoftwareCopyrightList,
  editSoftwareCopyright,
  deleteSoftwareCopyright,
  createSoftwareCopyright,
  importSoftwareCopyright,
  exportSoftwareCopyright,
  getSoftwareCopyrightTemplate,
} from "../actions/softwareCopyright";
import "../styles.css";

const { RangePicker } = DatePicker;

function SoftwareCopyrightTable(props) {
  const {
    dispatch,
    editSoftwareCopyrightResult,
    createSoftwareCopyrightResult,
    deleteSoftwareCopyrightResult,
    importSoftwareCopyrightResult,
  } = props;

  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [editingRecord, setEditingRecord] = useState(null);
  const [form] = Form.useForm();
  const [editForm] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [uploadFile, setUploadFile] = useState(null);
  const [importData, setImportData] = useState(null);
  const [uploading, setUploading] = useState(false);
  const [softwareCopyrightList, setSoftwareCopyrightList] = useState([]);

  // 获取软著列表
  const fetchSoftwareCopyrightList = (params = {}) => {
    setLoading(true);
    const queryParams = {
      page: params.current || pagination.current,
      pageSize: params.pageSize || pagination.pageSize,
      keyword: params.keyword || "",
      issueStartDate: params.issueStartDate || "",
      issueEndDate: params.issueEndDate || "",
      sortField: params.sortField || "id",
      sortOrder: params.sortOrder || "asc",
      ...params,
    };
    dispatch(getSoftwareCopyrightList(queryParams))
      .then((res) => {
        console.log("res", res);
        if (res && res.payload) {
          setSoftwareCopyrightList(res.payload.data);
          setPagination((prev) => ({
            ...prev,
            current: res.payload.data.page || prev.current,
            pageSize: res.payload.data.pageSize || prev.pageSize,
            total: res.payload.data.total || 0,
          }));
        }
        setLoading(false);
      })
      .catch(() => {
        setLoading(false);
      });
  };

  // 组件加载时获取数据
  useEffect(() => {
    fetchSoftwareCopyrightList();
  }, []);

  // 处理编辑结果
  useEffect(() => {
    if (editSoftwareCopyrightResult) {
      if (editSoftwareCopyrightResult.error) {
        message.error(
          editSoftwareCopyrightResult.message || "保存软著信息失败"
        );
      } else {
        message.success("保存软著信息成功");
        fetchSoftwareCopyrightList();
        setEditModalVisible(false);
      }
    }
  }, [editSoftwareCopyrightResult]);

  // 处理新增结果
  useEffect(() => {
    if (createSoftwareCopyrightResult) {
      if (createSoftwareCopyrightResult.error) {
        message.error(
          createSoftwareCopyrightResult.message || "新增软著信息失败"
        );
      } else {
        message.success("新增软著信息成功");
        fetchSoftwareCopyrightList();
        setEditModalVisible(false);
      }
    }
  }, [createSoftwareCopyrightResult]);

  // 列表数据更新时处理
  useEffect(() => {
    if (softwareCopyrightList) {
      setLoading(false);
      setPagination((prevPagination) => ({
        ...prevPagination,
        total: softwareCopyrightList.total,
        pageSize: softwareCopyrightList.pageSize || prevPagination.pageSize,
        current: softwareCopyrightList.page || prevPagination.current,
      }));
    }
  }, [softwareCopyrightList]);

  // 处理删除结果
  useEffect(() => {
    if (deleteSoftwareCopyrightResult) {
      message.success("删除软著成功");
      fetchSoftwareCopyrightList();
    }
  }, [deleteSoftwareCopyrightResult]);

  // 处理导入结果
  useEffect(() => {
    if (importSoftwareCopyrightResult) {
      if (importSoftwareCopyrightResult.duplicateMessage) {
        message.warning(importSoftwareCopyrightResult.duplicateMessage);
      }
      message.success(
        `成功导入${importSoftwareCopyrightResult.success || 0}条软著数据，失败${
          importSoftwareCopyrightResult.failed || 0
        }条`
      );
      fetchSoftwareCopyrightList();
      setModalVisible(false);
    }
  }, [importSoftwareCopyrightResult]);

  // 表格变化处理（分页、排序等）
  const handleTableChange = (pagination, filters, sorter) => {
    setPagination((prev) => ({
      ...prev,
      current: pagination.current,
      pageSize: pagination.pageSize,
    }));

    fetchSoftwareCopyrightList({
      current: pagination.current,
      pageSize: pagination.pageSize,
      sortField: sorter.field,
      sortOrder: sorter.order,
      ...filters,
    });
  };

  const onEdit = (record) => {
    setEditingRecord(record);
    editForm.setFieldsValue({
      ...record,
      disclosure_time: record.disclosure_time
        ? dayjs(record.disclosure_time)
        : null,
      development_complete_date: record.development_complete_date
        ? dayjs(record.development_complete_date)
        : null,
      acceptance_date: record.acceptance_date
        ? dayjs(record.acceptance_date)
        : null,
      issue_date: record.issue_date ? dayjs(record.issue_date) : null,
      first_publication_date: record.first_publication_date
        ? dayjs(record.first_publication_date)
        : null,
    });
    setEditModalVisible(true);
  };

  const onDelete = (record) => {
    Modal.confirm({
      title: "确认删除？",
      content: `确定要删除软著「${record.software_name}」吗？`,
      okText: "确认",
      cancelText: "取消",
      onOk: () => {
        dispatch(deleteSoftwareCopyright(record.id));
      },
    });
  };

  const handleEditOk = () => {
    editForm
      .validateFields()
      .then((values) => {
        const formattedValues = {
          ...values,
          disclosure_time: values.disclosure_time?.format("YYYY-MM-DD"),
          development_complete_date:
            values.development_complete_date?.format("YYYY-MM-DD"),
          acceptance_date: values.acceptance_date?.format("YYYY-MM-DD"),
          issue_date: values.issue_date?.format("YYYY-MM-DD"),
          first_publication_date:
            values.first_publication_date?.format("YYYY-MM-DD"),
        };

        if (editingRecord) {
          // 修改操作
          dispatch(editSoftwareCopyright(editingRecord.id, formattedValues)).catch((err) => {
            message.error("保存软著信息失败: " + (err.message || "未知错误"));
          });
        } else {
          // 新增操作
          dispatch(createSoftwareCopyright(formattedValues)).catch((err) => {
            message.error("新增软著信息失败: " + (err.message || "未知错误"));
          });
        }
      })
      .catch((err) => {
        message.error("表单验证失败，请检查必填字段");
    });
  };

  // 处理导入的数据格式化
  const handleFormatImportData = (data) => {
    // 可以根据实际需要对导入数据进行格式化
    return data;
  };

  // 验证导入文件
  const validateImportFile = (data) => {
    const errors = [];
    
    // 检查表头是否符合要求
    const requiredHeaders = ['软件名称', '登记号', '我司案号', '发明人'];
    const headers = data[0] || [];
    
    for (const header of requiredHeaders) {
      if (!headers.includes(header)) {
        errors.push(`导入文件缺少必要的列：${header}`);
      }
    }
    
    // 检查数据行
    if (data.length <= 1) {
      errors.push('导入文件没有数据行');
    }
    
    return errors;
  };

  // 处理文件上传和解密
  const handleCustomUpload = async ({ file, onSuccess, onError }) => {
    setUploading(true);
    
    // 文件类型校验
    const fileType = file.name.split('.').pop().toLowerCase();
    if (fileType !== 'xlsx' && fileType !== 'xls') {
      message.error('请上传正确的Excel文件');
      onError(new Error('请上传正确的Excel文件'));
      setUploading(false);
      return;
    }
    
    try {
      // 使用decodeFile函数进行文件解密
      const decodedBlob = await decodeFile(file);
      
      // 创建一个FileReader来读取解密后的文件内容
      const reader = new FileReader();
      reader.readAsArrayBuffer(decodedBlob);
      
      reader.onload = function(e) {
        try {
          const data = new Uint8Array(e.target.result);
          const workbook = XLSX.read(data, { type: 'array', cellDates: true });
          const name = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[name];
          let jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 }).filter(item => item.length > 0);
          
          // 格式化导入数据
          jsonData = handleFormatImportData(jsonData);
          
          // 验证导入文件
          const errors = validateImportFile(jsonData);
          
          if (errors.length > 0) {
            message.error(errors[0]);
            onError(new Error(errors[0]));
            setUploading(false);
            return;
          }
          
          // 设置导入数据
          setUploadFile(file);
          setImportData(jsonData);
          onSuccess();
          message.success('文件解析成功，请点击"导入"按钮完成导入');
          setUploading(false);
        } catch (error) {
          console.error('解析Excel文件失败:', error);
          message.error('解析Excel文件失败');
          onError(error);
          setUploading(false);
        }
      };
      
      reader.onerror = function() {
        message.error('读取文件失败');
        onError(new Error('读取文件失败'));
        setUploading(false);
      };
    } catch (error) {
      console.error('文件解密失败:', error);
      message.error('文件解密失败，请重试');
      onError(error);
      setUploading(false);
    }
  };

  // 执行导入操作
  const handleImport = () => {
    if (!uploadFile) {
      message.error("请先选择要导入的Excel文件");
      return;
    }

    setUploading(true);
    
    // 如果有解析的导入数据，使用它来构建导入数据
    if (importData && importData.length > 1) {
      // 假设表头是第一行，数据从第二行开始
      const headers = importData[0];
      const dataRows = importData.slice(1);
      
      // 将数据转换为适合API的格式
      const formattedData = dataRows.map(row => {
        const item = {};
        headers.forEach((header, index) => {
          // 根据表头和实际字段进行映射
          switch(header) {
            case '软件名称':
              item.software_name = row[index];
              break;
            case '登记号':
              item.registration_number = row[index];
              break;
            case '我司案号':
              item.case_number = row[index];
              break;
            case '发明人':
              item.inventors = row[index];
              break;
            case '技术交底书收集时间':
              item.disclosure_time = row[index] ? dayjs(row[index]).format('YYYY-MM-DD') : null;
              break;
            case '开发完成日期':
              item.development_complete_date = row[index] ? dayjs(row[index]).format('YYYY-MM-DD') : null;
              break;
            case '受理时间':
              item.acceptance_date = row[index] ? dayjs(row[index]).format('YYYY-MM-DD') : null;
              break;
            case '发证时间':
              item.issue_date = row[index] ? dayjs(row[index]).format('YYYY-MM-DD') : null;
              break;
            case '关联产品':
              item.related_product = row[index];
              break;
            case '关联立项/课题':
              item.related_project = row[index];
              break;
            case '防御型/攻击型':
              item.type = row[index];
              break;
            case '首次发表日期':
              item.first_publication_date = row[index] ? dayjs(row[index]).format('YYYY-MM-DD') : null;
              break;
            case '著作权人':
              item.copyright_holder = row[index];
              break;
            case '状态':
              item.status = row[index];
              break;
            case '是否为核心':
              item.is_core = row[index] === '是' ? true : false;
              break;
            case '核心分数':
              item.core_score = row[index];
              break;
            case '来源部门':
              item.source_department = row[index];
              break;
            case '代理负责人':
              item.agent_responsible = row[index];
              break;
            default:
              // 其他字段可以根据需要映射
              break;
          }
        });
        return item;
      });
      
      // 检查必填字段
      const invalidItems = formattedData.filter(item => !item.software_name || !item.registration_number);
      if (invalidItems.length > 0) {
        message.error(`有 ${invalidItems.length} 条数据缺少软件名称或登记号`);
        setUploading(false);
        return;
      }
      
      // 发送导入请求
      dispatch(importSoftwareCopyright({ items: formattedData }))
        .then(() => {
          setUploading(false);
        })
        .catch(err => {
          console.error('导入失败:', err);
          message.error('导入失败: ' + (err.message || '未知错误'));
          setUploading(false);
        });
    } else {
      // 如果没有解析的数据，使用传统方式上传文件
      const formData = new FormData();
      formData.append("file", uploadFile);
      
      dispatch(importSoftwareCopyright(formData))
        .then(() => {
          setUploading(false);
        })
        .catch(err => {
          console.error('导入失败:', err);
          message.error('导入失败: ' + (err.message || '未知错误'));
          setUploading(false);
        });
    }
  };

  // 导出软著数据
  const handleExport = () => {
    const values = form.getFieldsValue();
    const params = {
      keyword: values.keyword || "",
      issueStartDate:
        values.issueDateRange && values.issueDateRange[0]
          ? values.issueDateRange[0].format("YYYY-MM-DD")
          : "",
      issueEndDate:
        values.issueDateRange && values.issueDateRange[1]
          ? values.issueDateRange[1].format("YYYY-MM-DD")
          : "",
    };

    // 构建导出URL
    const queryString = Object.keys(params)
      .filter((key) => params[key])
      .map((key) => `${key}=${encodeURIComponent(params[key])}`)
      .join("&");

    const exportUrl = `${window.location.origin}/_api/softwareCopyright/export?${queryString}`;

    // 创建一个临时链接并点击，触发下载
    const link = document.createElement("a");
    link.href = exportUrl;
    link.target = "_blank";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  // 下载导入模板
  const handleDownloadTemplate = () => {
    const templateUrl = `${window.location.origin}/api/softwareCopyright/template`;

    const link = document.createElement("a");
    link.href = templateUrl;
    link.target = "_blank";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  // 获取表格列配置
  const columns = getColumns({
    onEdit,
    onDelete,
  });

  return (
    <div>
      <div
        className="search-area"
        style={{
          marginBottom: 16,
          padding: "16px",
          backgroundColor: "#f0f2f5",
          borderRadius: "4px",
        }}
      >
        <Form
          form={form}
          layout="inline"
          onFinish={(values) => {
            const params = {
              ...values,
              current: 1,
              issueStartDate:
                values.issueDateRange && values.issueDateRange[0]
                  ? values.issueDateRange[0].format("YYYY-MM-DD")
                  : null,
              issueEndDate:
                values.issueDateRange && values.issueDateRange[1]
                  ? values.issueDateRange[1].format("YYYY-MM-DD")
                  : null,
            };
            fetchSoftwareCopyrightList(params);
          }}
        >
          <Form.Item label="关键字:" name="keyword">
            <Input
              placeholder="软件名称、登记号、著作权人"
              style={{ width: 240 }}
            />
          </Form.Item>
          <Form.Item label="发证时间:" name="issueDateRange">
            <RangePicker style={{ width: 240 }} />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              onClick={() => {
                form.resetFields();
                fetchSoftwareCopyrightList({ current: 1 });
              }}
            >
              重置
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              onClick={() => {
                setEditingRecord(null);
                editForm.resetFields();
                setEditModalVisible(true);
              }}
              icon={<PlusOutlined />}
              style={{ marginRight: 8 }}
            >
              新增软著
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              onClick={() => setModalVisible(true)}
              icon={<UploadOutlined />}
              style={{ marginRight: 8 }}
            >
              导入软著
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              onClick={handleExport}
              icon={<DownloadOutlined />}
              style={{ marginRight: 8 }}
            >
              导出软著
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              onClick={handleDownloadTemplate}
              icon={<FileExcelOutlined />}
            >
              下载模板
            </Button>
          </Form.Item>
        </Form>
      </div>

      <div className="software-copyright-table-container">
        <Table
          columns={columns}
          dataSource={softwareCopyrightList?.data || []}
          rowKey="id"
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: ["10", "20", "50", "100"],
          }}
          loading={loading}
          onChange={handleTableChange}
          scroll={{ x: "max-content", y: 500 }}
          size="small"
          rowClassName={() => "custom-table-row"}
        />
      </div>

      {/* 导入软著弹窗 */}
      <Modal
        title="导入软著数据"
        open={modalVisible}
        onOk={handleImport}
        onCancel={() => {
          setModalVisible(false);
          setUploadFile(null);
          setImportData(null);
        }}
        confirmLoading={uploading}
        okText="导入"
        cancelText="取消"
      >
        <Upload
          customRequest={handleCustomUpload}
          showUploadList={{ showRemoveIcon: true }}
          fileList={uploadFile ? [uploadFile] : []}
          onRemove={() => {
            setUploadFile(null);
            setImportData(null);
          }}
          maxCount={1}
          accept=".xlsx,.xls"
        >
          <Button icon={<UploadOutlined />} loading={uploading} disabled={uploading}>
            选择Excel文件
          </Button>
        </Upload>
        <div style={{ marginTop: 16 }}>
          <p>注意：导入前请确保数据格式正确，软件名称和登记号为必填项</p>
          <p>如需模板，请点击"下载模板"按钮</p>
          {uploading && <p>正在处理文件，请稍候...</p>}
        </div>
      </Modal>

      {/* 编辑/新增软著弹窗 */}
      <Modal
        title={editingRecord ? "编辑软著信息" : "新增软著信息"}
        open={editModalVisible}
        onOk={handleEditOk}
        onCancel={() => setEditModalVisible(false)}
        width={1000}
        bodyStyle={{ maxHeight: "600px", overflow: "auto" }}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={editForm}
          layout="horizontal"
          labelCol={{ flex: "160px" }}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Row gutter={16}>
            {[
              ["software_name", "软件名称", <Input />, true],
              ["case_number", "我司案号", <Input />, true],
              ["registration_number", "登记号", <Input />, true],
              ["inventors", "发明人", <Input />, true],
              [
                "disclosure_time",
                "技术交底书收集时间",
                <DatePicker style={{ width: "100%" }} />,
                true,
              ],
              [
                "development_complete_date",
                "开发完成日期",
                <DatePicker style={{ width: "100%" }} />,
                true,
              ],
              [
                "acceptance_date",
                "受理时间",
                <DatePicker style={{ width: "100%" }} />,
                true,
              ],
              [
                "issue_date",
                "发证时间",
                <DatePicker style={{ width: "100%" }} />,
                true,
              ],
              ["related_product", "关联产品", <Input />, true],
              ["related_project", "关联立项/课题", <Input />, true],
              [
                "type",
                "防御型/攻击型",
                <Select>
                  {typeOptions.map((option) => (
                    <Select.Option key={option} value={option}>
                      {option}
                    </Select.Option>
                  ))}
                </Select>,
                true,
              ],
              [
                "first_publication_date",
                "首次发表日期",
                <DatePicker style={{ width: "100%" }} />,
                true,
              ],
              ["copyright_holder", "著作权人", <Input />, true],
              [
                "status",
                "状态",
                <Select>
                  {statusOptions.map((option) => (
                    <Select.Option key={option} value={option}>
                      {option}
                    </Select.Option>
                  ))}
                </Select>,
                true,
              ],
              [
                "is_core",
                "是否为核心",
                <Switch checkedChildren="是" unCheckedChildren="否" />,
                true,
              ],
              [
                "core_score",
                "核心分数",
                <InputNumber min={0} max={100} style={{ width: "100%" }} />,
                true,
              ],
              ["source_department", "来源部门", <Input />, true],
              ["agent_responsible", "代理负责人", <Input />, true],
              ["original_name", "原名称", <Input />, false],
              [
                "dev_related_project",
                "（发展部）关联课题/项目",
                <Input />,
                false,
              ],
              [
                "special_notes",
                "特殊事项备注",
                <Input.TextArea rows={2} />,
                false,
              ],
            ].map(([name, label, component, required]) => (
              <Col span={12} key={name}>
                <Form.Item
                  name={name}
                  label={label}
                  valuePropName={
                    component.type === Switch ? "checked" : "value"
                  }
                  rules={[{ required: required, message: `请输入${label}` }]}
                >
                  {component}
                </Form.Item>
              </Col>
            ))}
          </Row>
        </Form>
      </Modal>
    </div>
  );
}

function mapStateToProps(state) {
  const {
    softwareCopyrightList,
    editSoftwareCopyrightResult,
    deleteSoftwareCopyrightResult,
    createSoftwareCopyrightResult,
    importSoftwareCopyrightResult,
    exportSoftwareCopyrightResult,
    softwareCopyrightTemplate,
  } = state.softwareCopyright || {};
  return {
    softwareCopyrightList,
    editSoftwareCopyrightResult,
    deleteSoftwareCopyrightResult,
    createSoftwareCopyrightResult,
    importSoftwareCopyrightResult,
    exportSoftwareCopyrightResult,
    softwareCopyrightTemplate,
  };
}

export default connect(mapStateToProps)(SoftwareCopyrightTable);
